package org.robot.scm.platform.server.telegram;

import it.tdlight.client.SimpleAuthenticationSupplier;
import it.tdlight.client.SimpleTelegramClient;
import it.tdlight.client.SimpleTelegramClientBuilder;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.AuthorizationState;
import it.tdlight.jni.TdApi.MessageSenderUser;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class ScmTelegram {

    @Getter
    private final SimpleTelegramClient client;

    @Getter
    private final String socks5;

    @Getter
    private final long adminId;

    public ScmTelegram(SimpleTelegramClientBuilder clientBuilder, SimpleAuthenticationSupplier<?> authenticationData, long adminId, String socks5, TelegramRobot robot, ClientSetCall clientSetCall) {
        this.adminId = adminId;
        this.socks5 = socks5;

        // Add an example update handler that prints when the bot is started
        clientBuilder.addUpdateHandler(TdApi.UpdateAuthorizationState.class, this::onUpdateAuthorizationState);

        // Add an example command handler that stops the bot
        clientBuilder.addCommandHandler("stop", this::onStopCommand);

        // Add an example update handler that prints every received message
        clientBuilder.addUpdateHandler(TdApi.UpdateNewMessage.class, update -> robot.onUpdate(update, this));

        // Build the client
        this.client = clientBuilder.build(authenticationData);

        clientSetCall.onUpdate(this);

        // add socks5 proxy
        if (StringUtils.isNotBlank(socks5)) {
            log.info("telegram socks5 ... ok");
            this.client.send(new TdApi.AddProxy(socks5.split(":")[0], Integer.parseInt(socks5.split(":")[1]), true, new TdApi.ProxyTypeSocks5()));
        }
    }

    /**
     * Print the bot status
     */
    private void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) {
        AuthorizationState authorizationState = update.authorizationState;
        if (authorizationState instanceof TdApi.AuthorizationStateReady) {
            log.info("telegram login ... ok");
        } else if (authorizationState instanceof TdApi.AuthorizationStateClosing) {
            log.info("telegram closing");
        } else if (authorizationState instanceof TdApi.AuthorizationStateClosed) {
            log.info("telegram closed");
        } else if (authorizationState instanceof TdApi.AuthorizationStateLoggingOut) {
            log.info("telegram logout");
        }
    }

    /**
     * Close the bot if the /stop command is sent by the administrator
     */
    private void onStopCommand(TdApi.Chat chat, TdApi.MessageSender commandSender, String arguments) {
        // Check if the sender is the admin
        if (isAdmin(commandSender)) {
            // Stop the client
            log.info("Received stop command. closing...");
            client.sendClose();
        }
    }

    /**
     * Check if the command sender is admin
     */
    public boolean isAdmin(TdApi.MessageSender sender) {
        if (sender instanceof MessageSenderUser) {
            MessageSenderUser messageSenderUser = (MessageSenderUser) sender;
            return messageSenderUser.userId == adminId;
        } else {
            return false;
        }
    }
}
